#include<iostream>
#include <deque>
#include <cstring>

using namespace std;

typedef pair<int, int> PII;

const int N = 1e3 + 10;

char a[N][N];
int n,m;
int dist[4][N][N];

int dx[] = { 0,0,1,-1 };
int dy[] = { 1,-1,0,0 };
void bfs(int num)
{
	memset(dist, -1, sizeof dist);
	deque<PII> q;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
		{
			if(a[i][j] - '0' == num)
			{
				q.push_front({i,j});
				dist[num][i][j] = 0;
			}
		}
	while(q.size())
	{
		auto t = q.front(); q.pop_front();
		int i = t.first, j = t.second;
		for (int k = 0; k < 4; k++)
		{
			int x = i + dx[k], y = j + dy[k];
			int w = a[num][x][y] == '.' ? 1 : 0; 
			if (x >= 1 && x <= n && y >= 1 && y <= n && a[i][j] != '#')
			{
				if(dist[x][y] == -1)
				{
					dist[x][y] = dist[i][j] + w;
					if(a[x][y] - '0' == num)
						q.push_front({x,y});
					else
						q.push_back({x,y});
				}
				else if(dist[x][y] > dist[i][j] + w)
				{
					dist[x][y] = dist[i][j] + w;
				}
			}
		}
	}
}
int main()
{
	cin >> n >> m;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
			cin >> a[i][j];
	bfs(1); bfs(2); bfs(3);
	
	int ret = 1e9;
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= m; j++)
		{
			int a = dist[1][i][j], b = dist[2][i][j], c = dist[3][i][j];
			if (a[i][j] == '#')	continue;
			else if (a[i][j] == '.') ret = min(ret, a + b + c)
			else ret = min(ret, a + b + c - 2);		
		}
	cout << ret << endl;
	return 0;
}
